package com.serialstamper.api.wrapper.converters;


import com.serialstamper.api.wrapper.model.File;
import com.serialstamper.api.wrapper.model.FileTimestamp;
import com.serialstamper.api.wrapper.model.FileUser;
import com.serialstamper.api.wrapper.model.HashAlgorithm;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class FileUserConverter extends ModelConverter {
	
	public FileUserConverter() {
		super(FileUser.class);
	}
	
	@Override
	public String getAlias() {
		return "user";
	}
	
	@Override
	public void marshal(Object source, HierarchicalStreamWriter writer,
			MarshallingContext context) {
		FileUser user = (FileUser)source;
		// Marshal only updatable fields
		marshalFieldValue(context, writer, "id", user.getUserId());
		marshalField(context, writer, user, "metadata");
	}

	@Override
	public Object unmarshal(HierarchicalStreamReader reader,
			UnmarshallingContext context) {
		FileUser fu = new FileUser();
        while (reader.hasMoreChildren()) {
            reader.moveDown();

            String propertyName = reader.getNodeName();
            if ("id".equals(propertyName)) {
            	propertyName = "userId";
            }
            Object value = context.convertAnother(fu, getFieldClass(propertyName));
            setFieldValue(fu, propertyName, value);

            reader.moveUp();
        }
		return fu;
	}
}
